<template>
  <div style="width: 100%; height: 100%">
    <guangbopanelCard :headerFlag="true">
      <template #header>
        <div style="display: flex; align-items: center">
          <div style="width: 30%; display: flex; align-items: center">
            <span>时间选择</span>
            <el-date-picker
              style="margin-left: 15px"
              v-model="state.searchData.time"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :disabled-date="disabledDate"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 1, 1, 23, 59, 59),
              ]"
            />
          </div>
          <div style="margin-left: 40px">
            <el-button @click="queryFn" type="primary">查询</el-button>
            <el-button @click="resetFn">重置</el-button>
          </div>
        </div>
      </template>
      <template #article>
        <guangbovxeTB
          ref="guangbovxeTB"
          title="录音记录"
          :tableheads_show="state.tableheads_show"
          :listUrl="state.listUrl"
          :caozuoList="state.caozuoList"
          @delAllFn="delAllFn"
          @bofangluyin="bofangluyinFn"
        ></guangbovxeTB>
      </template>
    </guangbopanelCard>
    <!-- 播放录音 -->
    <el-dialog
      v-model="state.bofangFlag"
      width="28%"
      :before-close="bofanghandleClose"
    >
      <template #title>
        <span class="themfontColor">播放录音</span>
      </template>
      <div style="width: 100%">
        <el-row>
          <!-- <el-col :span="12">
            <span>呼叫终端：</span
            ><span>{{ state.bofangData.FromTerminalNO }}</span></el-col
          >
          <el-col :span="12">
            <span>被呼叫终端：</span
            ><span>{{ state.bofangData.ToTerminalNO }}</span></el-col
          > -->
          <el-col :span="12">
            <span class="el-form-item__label">参与终端：</span
            ><span class="el-form-item__label">{{
              state.bofangData.TerminalList
            }}</span></el-col
          >
          <el-col :span="12">
            <span class="el-form-item__label">通话时间：</span
            ><span class="el-form-item__label">{{
              state.bofangData.Duration
            }}</span></el-col
          >
        </el-row>
        <el-row style="margin: 10px 0">
          <el-col :span="24">
            <span class="el-form-item__label">录音名称：</span
            ><span class="el-form-item__label">{{
              state.bofangData.FileName ? state.bofangData.FileName : "无"
            }}</span></el-col
          >
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center"
            ><audio ref="audioPlayer" controls autoplay></audio>
          </el-col>
        </el-row>
      </div>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveAddFn"> 确定 </el-button>
        </div>
      </template> -->
    </el-dialog>
  </div>
</template>

<script setup>
import { nextTick, onMounted, reactive } from "vue-demi";
import axios from "@/utils/request";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { table_headers } from "@/assets/table_headers/table_headers";
import usepagesStore from "@/store/modules/pages";
const userStore = usepagesStore();
const { proxy } = getCurrentInstance();
import { Base64 } from "js-base64";
import dayjs from "dayjs";
const props = defineProps({});
const emit = defineEmits([""]);
const disabledDate = (time) => {
  return time.getTime() >= Date.now() - 8.64e7 / 4; // 8.64e7 毫秒数代表一天
};
let state = reactive({
  addTitle: "新增",
  searchData: { PlaceDic: 0 },
  form: {},
  bofangFlag: false, //播放录音
  caozuoList: [
    {
      caozuoType: "bofangluyin",
      label: "播放录音",
      type: "text",
    },
  ],
  tabledata: [],
  tableheads_show: computed(() => table_headers.t_sip_file_record),
  bofangData: [], //播放录音
  audioUrl: "",
  listUrl: "/sip/fileRecord/list",
  addUrl: "/sip/config/file/add",
  editUrl: "/sip/config/file/edit",
  delUrl: "/sip/config/file/",
  detailUrl: "/sip/fileRecord/",
});
function timeFn() {
  // let time = dayjs().format("YYYY-MM-DD");
  let time2 = dayjs().format("YYYY-MM-DD HH:mm:ss");
  // let time3 = dayjs().format("HH:mm:ss");
  // let hours = time3.substr(0, 2) - 1;
  // let str = time3.substr(2, 6);
  // let str2 = hours + str;
  // let str=time2.substring(5,7)
  let str2 = Number(time2.substring(5, 7));

  if (str2 != 1) {
    let val = str2 - 1;
    let value = val < 10 ? "0" + val : val;
    let time = dayjs().format("YYYY-MM-DD");
    let value2 = time.split("");
    value2[5] = value.split("")[0];
    value2[6] = value.split("")[1];
    let result =
      value2[0] +
      value2[1] +
      value2[2] +
      value2[3] +
      value2[4] +
      value2[5] +
      value2[6] +
      value2[7] +
      value2[8] +
      value2[9] +
      " 00:00:00";
    state.searchData.time = [result, time2];
  }
}
const bofangluyinFn = (row) => {
  //播放录音
  console.log(row, "row");
  state.bofangData = row;
  if (row.file && row.file.id) {
    axios
      .get(`/common/downloadRecord?fileId=${row.file.id}`, {
        // params: {
        //   fileId: row.id,
        // }
        responseType: "blob",
      })
      .then((res) => {
        console.log(res, "res");
        playAudio(res);
        // if (res.DataList?.length >= 0) {
        //   if (res.DataList[0].FileDatastr) {
        //     state.bofangData.FileName = res.DataList[0].FileName;
        //     playAudio(res.DataList[0].FileDatastr);
        state.bofangFlag = true;
        //   } else {
        //     ElMessage.error("录音文件不存在");
        //   }
        // }
      });
  } else {
    ElMessage.warning("录音文件不存在");
  }
};
const playAudio = async (filePath) => {
  try {
    setTimeout(() => {
      //二进制流播放
      const blob = new Blob([filePath], { type: "audio/wav" });
      const audioUrl = URL.createObjectURL(blob);
      proxy.$refs["audioPlayer"].src = audioUrl;
      // proxy.$refs["audioPlayer"].src = `data:audio/mpeg;base64,${filePath}`;
      proxy.$refs["audioPlayer"].load(); //重新加载
      // proxy.$refs['audioPlayer'].play();
      proxy.$refs["audioPlayer"].pause(); //暂停
      //播放结束后需手动释放临时 URL 避免内存泄漏
      proxy.$refs["audioPlayer"].onended = () => {
        URL.revokeObjectURL(audioUrl);
      };
    }, 500);
  } catch (error) {
    console.error("播放失败:", error);
  }
};
const bofanghandleClose = () => {
  proxy.$refs["audioPlayer"].src = null;
  state.bofangFlag = false;
};
const delAllFn = () => {
  if (userStore.records.length == 0) {
    ElMessage.warning("请选择要删除的记录");
    return;
  } else {
    let str = [];
    userStore.records.forEach((item) => {
      str.push(item.id);
    });
    ElMessageBox.confirm("确认删除?", "提示", {
      confirmButtonText: "删除",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        axios.delete(state.delUrl + str.join(",")).then((res) => {
          ElMessage.success("删除成功");
          userStore.records = [];
          proxy.$refs["guangbovxeTB"].getList();
        });
      })
      .catch(() => {});
  }
};
const queryFn = () => {
  //查询
  let obj = {};
  obj.queryStartTime = state.searchData?.time?.[0];
  obj.queryEndTime = state.searchData?.time?.[1];
  proxy.$refs["guangbovxeTB"].state.searchData = obj;
  proxy.$refs["guangbovxeTB"].getList();
};
const resetFn = () => {
  //重置
  let obj = {};
  state.searchData = { PlaceDic: "" };
  proxy.$refs["guangbovxeTB"].state.searchData = {};
  timeFn();
  obj.queryStartTime = state.searchData?.time?.[0];
  obj.queryEndTime = state.searchData?.time?.[1];
  proxy.$refs["guangbovxeTB"].state.searchData = obj;
  proxy.$refs["guangbovxeTB"].getList();
};
onMounted(() => {
  timeFn();
  queryFn();
});
</script>